package com.qire.manhua.model.viewModel.impl;

import android.view.View;

import com.qire.common.basic.ObjectUtil;
import com.qire.common.basic.StringUtil;
import com.qire.common.collect.ArrayUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.support.SmartRefreshViewModel;
import com.qire.common.support.base.IViewModel;
import com.qire.common.utils.ToastHelper;
import com.qire.common.widget.adapter.auto.AutoVariable;
import com.qire.common.widget.adapter.auto.SummerRecyclerBindAdapter;
import com.qire.common.widget.adapter.auto.annotation.AdapterEntityBind;
import com.qire.manhua.BR;
import com.qire.manhua.R;
import com.qire.manhua.controller.ComicCommentReplyController;
import com.qire.manhua.databinding.LayoutComicCommentReplyItemBinding;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.entity.ComicComment;
import com.qire.manhua.dal.service.ComicCommentReplyService;

import java.util.ArrayList;

import androidx.databinding.BaseObservable;
import androidx.databinding.Bindable;
import androidx.lifecycle.MutableLiveData;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView.Adapter;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;

/**
 * 漫画评论详情回复页
 */
public class ComicCommentReplyViewModel extends SmartRefreshViewModel<IViewModel> implements IViewModel {

    private final ComicCommentReplyService commentReplyService = new ComicCommentReplyService(this);

    /** 引用参照评论的回复评论列表 */
    private final ArrayList<ComicCommentReplyItemViewModel> replyCommentList = new ArrayList<>();
    private final SummerRecyclerBindAdapter<ComicCommentReplyItemViewModel> replyCommentAdapter = new SummerRecyclerBindAdapter<>(replyCommentList);

    /** 回复的目标评论 */
    private ComicCommentReplyItemViewModel replyToTarget;

    /** 引用参照评论（需要展示详情的评论） */
    private ComicCommentReplyItemViewModel referComment;

    private ComicBookEntity comicBookEntity;

    private int pageNo = 1;

    @Override
    public int getVariableId() {
        return BR.comicCommentReplyViewModel;
    }

    //region    #附加管理 begin
    /**
     * 附加属性绑定
     * @param controller 事件控制器
     */
    public void onAddition(ComicCommentReplyController controller) {
        replyCommentAdapter.setEventProcess(controller);
    }

    /**
     * 清理函数，在Activity退出时，ViewModel生命周期到期会被回收，调用该事件，
     * 页面由于切换、横竖屏转换、内存回收等情况并不会影响到ViewModel的生命周期。
     */
    @Override
    protected void onCleared() {
        super.onCleared();
        this.comicBookEntity = null;
        this.replyCommentAdapter.setEventProcess(null);
    }
    //endregion #附加管理 end

    //region #业务数据

    public void nextPage() {
        this.pageNo++;
    }

    private void resetPage() {
        this.pageNo = 1;
        clearReplyCommentList();
    }

    private int comicBookId() {
        return comicBookEntity.id;
    }

    /**
     * 加载引用评论数据
     * @param comicBookEntity 评论所属漫画对象
     * @param comicComment 引用展示详情的评论对象
     */
    public void loadCommentData(ComicBookEntity comicBookEntity, ComicComment comicComment) {
        this.comicBookEntity = comicBookEntity;
        this.referComment = new ComicCommentReplyItemViewModel(comicComment);
        refreshReferCommentPanelUI();
        setReplyToTarget(referComment);
    }

    /**
     * 重置加载回复评论列表数据
     */
    public void loadReplyCommentListData() {
        resetPage();
        loadMoreReplyCommentListData();
    }

    /**
     * 加载更多回复评论列表数据
     */
    public void loadMoreReplyCommentListData() {
        commentReplyService.loadReplyCommentListData(comicBookId(), referComment.id(), pageNo);
    }

    /**
     * 清理漫画回复列表
     */
    private void clearReplyCommentList() {
        replyCommentAdapter.notifyItemRangeRemoved(0, replyCommentList.size());
        replyCommentList.clear();
    }

    /**
     * 加载回复评论数据
     * @param comments 回复评论列表
     */
    public void loadComicComment(ComicComment[] comments) {
        if(ArrayUtil.isEmpty(comments)) {
            return;
        }
        for(ComicComment comment : comments) {
            replyCommentList.add(new ComicCommentReplyItemViewModel(comment));
        }
        replyCommentAdapter.notifyItemChanged(0, "full");
        refreshCommentPanelUI();
    }

    /**
     * 提交回复评论到指定回复评论目标
     */
    public boolean submitReply() {
        if(ObjectUtil.isNull(replyToTarget)) {
            ToastHelper.showToast("请选择想要回复的评论");
            return true;
        }
        String replyContent =  getToValue("replyEditText");
        if(StringUtil.isEmpty(replyContent)) {
            ToastHelper.showToast("发送内容不能为空");
            return false;
        }
        if(replyContent.length() < 10) {
            ToastHelper.showToast("评论不能少于10个字");
            return false;
        }
        if(replyContent.length() > 200) {
            ToastHelper.showToast("请控制字数在200字以内");
            return false;
        }
        commentReplyService.replyComment(comicBookId(), replyToTarget.id(), replyContent);
        return true;
    }

    //endregion #业务数据

    //region #UI操作

    public void refreshCommentPanelUI() {
        boolean isEmptyData = ListUtil.isEmpty(replyCommentList);
        put("replyDataPanelNo", isEmptyData ? 0 : 1);
    }

    /**
     * 刷新引用评论的相关信息显示UI
     */
    private void refreshReferCommentPanelUI() {
        set("referComment", referComment);
        set("repliesCount", referComment.comicComment.replyCountToString() + "人回复");
    }

    /**
     * 设置指定的回复评论目标
     * @param replyToTarget 指定的回复评论目标
     */
    public void setReplyToTarget(ComicCommentReplyItemViewModel replyToTarget) {
        this.replyToTarget = replyToTarget;
        set("replyEditHintText", "回复 " + replyToTarget.userName() + ":");
    }

    /**
     * 评论成功后刷新回复后的UI
     */
    public void refreshReplyUI() {
        put("replyEditText", "");
        replyToTarget.addReply();
        if(replyToTarget == referComment) {
            set("repliesCount", referComment.comicComment.replyCountToString() + "人回复");
        }
    }

    //endregion #UI操作

    //region #UI绑定

    /** 引用参照评论（需要展示详情的评论）绑定 */
    public MutableLiveData<ComicCommentReplyItemViewModel> getReplyToTarget() {
        return get("referComment");
    }

    public MutableLiveData<String> getRepliesCount() {
        return get("repliesCount");
    }

    public MutableLiveData<Integer> getReplyDataPanelNo() {
        return get("replyDataPanelNo");
    }

    public MutableLiveData<String> getReplyEditHintText() {
        return get("replyEditHintText");
    }

    public MutableLiveData<String> getReplyEditText() {
        return get("replyEditText");
    }

    public Adapter getReplyCommentAdapter() {
        return replyCommentAdapter;
    }

    public LayoutManager getReplyCommentLayoutManager() {
        return new LinearLayoutManager(null);
    }

    //endregion #UI绑定

    @AdapterEntityBind(viewRid = R.layout.layout_comic_comment_reply_item)
    public class ComicCommentReplyItemViewModel extends BaseObservable implements AutoVariable<LayoutComicCommentReplyItemBinding> {

        public final ComicComment comicComment;

        public ComicCommentReplyItemViewModel(ComicComment comicComment) {
            this.comicComment = comicComment;
        }

        @Override
        public void bindVariable(LayoutComicCommentReplyItemBinding viewBind) {
            viewBind.setComicCommentReplyItemViewModel(this);
        }

        public boolean isMyLike() {
            return this.comicComment.isMyLike();
        }

        public int id() {
            return comicComment.id;
        }

        public String userName() {
            return this.comicComment.userName;
        }

        public String content() {
            return this.comicComment.content.toString();
        }

        public void addReply() {
            this.comicComment.addReply();
            notifyPropertyChanged(BR.replyCount);
        }

        /**
         * 点赞
         */
        public void giveAlike() {
            this.comicComment.likeCountUp();
            commentReplyService.voteToGiveLikeComment(comicBookId(), this.comicComment.id);
            notifyPropertyChanged(BR.thumbsUpRes);
            notifyPropertyChanged(BR.likeCount);
        }

        /**
         * 举报
         * @param type 举报类型
         * @param content 举报内容
         */
        public void complaint(int type, String content) {
            commentReplyService.complaintComment(comicBookId(), this.comicComment.id, type, content);
        }

        @Bindable
        public int getPortraitFloatIconVisible() {
            return this.comicComment.isVip() ? View.VISIBLE : View.GONE;
        }

        @Bindable
        public String getPortraitPath() {
            return this.comicComment.userPortrait;
        }

        @Bindable
        public String getUserName() {
            return this.comicComment.userName;
        }

        @Bindable
        public String getUserNameColor() {
            return this.comicComment.isVip() ? "#ff5050" : "#666666";
        }

        @Bindable
        public CharSequence getContent() {
            return this.comicComment.content;
        }

        @Bindable
        public String getCreateTime() {
            return this.comicComment.createTime;
        }

        @Bindable
        public int getThumbsUpRes() {
            return this.comicComment.isMyLike() ? R.drawable.app_comic_detail_comment_icon_give_like_b : R.drawable.app_comic_detail_comment_icon_give_like_a;
        }

        @Bindable
        public String getLikeCount() {
            return StringUtil.toSymbol(this.comicComment.likeCount());
        }

        @Bindable
        public String getReplyCount() {
            return this.comicComment.replyCountToString();
        }

    }

}
